//
//  MediaBookXMLParser.m
//  Dolphin
//
//  Created by Handymood on 11-5-25.
//  Copyright 2011 __Hanydmood__. All rights reserved.
//

#import "MediaBookXMLParser.h"

@implementation MediaBookXMLParser

@synthesize pagesArr;
@synthesize projectsArr;
@synthesize gDataSet;
@synthesize upToolBarInfo;
@synthesize bottomIndexPage;
@synthesize isIPad;
@synthesize msgString;
@synthesize propData;

-(id) init
{
    msgString = @"load_book_xml_over";
    
    return self;
}

-(void)startParsing:(NSString *) inXMLAddress
{
    dataReceiveErr = FALSE;
    
    NSString *fileNamePrefix = [inXMLAddress  substringWithRange:NSMakeRange(0, [inXMLAddress  length] - 4)];
    NSString *fileNameSuffix = [inXMLAddress substringWithRange:NSMakeRange([inXMLAddress length]-3,3)];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:fileNamePrefix ofType:fileNameSuffix];
    NSData *xmlData = [NSData dataWithContentsOfFile:path];
    
    BOOL loadXmlFromWeb = FALSE;
    
    if([inXMLAddress length] > 11) 
    {
        NSString *httpSuffix = [inXMLAddress substringWithRange:NSMakeRange(0,7)];
        
        if([[httpSuffix lowercaseString] isEqualToString:@"http://"])
        {
            loadXmlFromWeb = YES;
            
            NSURL *url = [NSURL URLWithString:inXMLAddress];
            xmlDataBuffer = [[NSMutableData alloc] init];
            xmlLoadConnect = [[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self] retain];
            [xmlLoadConnect start];
        }
    }
    
    if (!loadXmlFromWeb)
    {
        xmlTextReaderPtr xmlreader = xmlReaderForMemory([xmlData bytes], 
                                                        [xmlData length], 
                                                        [path UTF8String], nil, 
                                                        (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
        [self xmlParseProc:xmlreader];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    int statusCode = [((NSHTTPURLResponse *) response) statusCode];
    if (statusCode >= 400 && dataReceiveErr == FALSE)
    {
        UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Web connection fail, please try later." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
        [av show];
        dataReceiveErr = TRUE;
    }
    
    [xmlDataBuffer setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (dataReceiveErr) 
    {
        return;
    }
    
    [xmlDataBuffer appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (dataReceiveErr)
    {
        return;
    }
    
    xmlTextReaderPtr xmlreader = xmlReaderForMemory([xmlDataBuffer  bytes], 
                                                    [xmlDataBuffer  length], 
                                                    nil, nil, 
                                                    (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
    [self xmlParseProc:xmlreader];
    
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    dataReceiveErr = TRUE;
    UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Web connection fail, please try later." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [av show];
}

-(void) xmlParseProc:(xmlTextReaderPtr) xmlreader
{
    isIPad = TRUE;
    
    if (!xmlreader) 
    {
        NSLog(@"xmlreader load failure");
        return;
    }
    
    //init the data for read
    pagesArr = [[NSMutableArray alloc] init];//array store the page's data.
    projectsArr = [[NSMutableArray alloc] init];
    
    gDataSet = [[GlobalSet alloc] init];
    [gDataSet initDefaultSet];
    
    //upToolBarInfo = [[UpToolBarInfo alloc] init];
    bottomIndexPage = [[IndexPageInfo alloc] init];
    propData = [[TagData alloc] init];
    
    //[upToolBarInfo initDefaultSet];
    [bottomIndexPage initDefaultSet];
    [propData initDefaultSet];
    
    //NSMutableArray *layerArr = [[NSMutableArray alloc] init]; // the layers array for per pages
    SinglePageInfo *tempPageInfo = [[SinglePageInfo alloc] init];
    //LayerInfo *tempLayerInfo = [[LayerInfo alloc] init];
    
    NSString *tempTagName = Nil;
    NSString *tempTagValue = Nil; 
    NSString *currentTag = Nil;
    char *tempData;
    int count = 0;
    int tag_count = 0;
    
    while (true) 
    {
        if (!xmlTextReaderRead(xmlreader))
        {    
            break;
        }
        
        //xml validate check
        count++; 
        if (count>100000) 
        {
            count = -1;
            break;
        }
        
        int curtype = xmlTextReaderNodeType(xmlreader);
        
        switch (curtype) 
        {
            case XML_READER_TYPE_ELEMENT:
                //We are starting an element
                tempData =  (char*)xmlTextReaderConstName(xmlreader);
                
                tempTagName = [NSString stringWithCString:tempData 
                                                 encoding:NSUTF8StringEncoding];
                
                if ([tempTagName isEqualToString:@"ad"]) //init the global set data
                {
                    currentTag = @"ad";
                    tag_count++;
                }
                else if([tempTagName isEqualToString:@"man"])
                {
                    currentTag = @"man";
                    tag_count++;
                }
                else if([tempTagName isEqualToString:@"cchar"])
                {
                    currentTag = @"cchar";
                    tag_count++;
                }
                else if([tempTagName isEqualToString:@"unit"])
                {
                    currentTag = @"unit";
                }
                else if([tempTagName isEqualToString:@"feed"])
                {
                    currentTag = @"feed";
                }
                else if([tempTagName isEqualToString:@"projects"])//init the page set unit
                {                    
                    currentTag = @"projects";
                }
                else if([tempTagName isEqualToString:@"imgs"])//init the page set unit
                {                    
                    currentTag = @"imgs";
                }
                else if([tempTagName isEqualToString:@"proj"] || [tempTagName isEqualToString:@"img"])//init the page set unit
                {
                    tempPageInfo = [[SinglePageInfo alloc] init];
                    [tempPageInfo defaultValueInit];
                    [self preDefaultGlobalDataToSinglePage:tempPageInfo];
                    [projectsArr addObject:tempPageInfo];
                }
                continue;
            case XML_READER_TYPE_TEXT: 
                tempData = (char*)xmlTextReaderConstValue(xmlreader);
                tempTagValue = [NSString stringWithCString:tempData
                                                  encoding:NSUTF8StringEncoding];
                
                if([currentTag isEqualToString:@"ad"])
                {
                    if([tempTagName isEqualToString:@"img"])
                    {
                        gDataSet.featureImg = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"url"])
                    {
                        gDataSet.featureUrl = tempTagValue;
                    }
                }
                else if([currentTag isEqualToString:@"man"] || 
                           [currentTag isEqualToString:@"feed"] ||
                           [currentTag isEqualToString:@"unit"] )
                {
                    if ([tempTagName isEqualToString:@"id"]) 
                    {
                        propData._id = tempTagValue;
                    }
                    else if ([tempTagName isEqualToString:@"name"]) 
                    {
                        propData.name = tempTagValue;
                    }
                    else if ([tempTagName isEqualToString:@"url"])
                    {
                        propData.url = tempTagValue;
                    }
                    else if ([tempTagName isEqualToString:@"digest"])
                    {
                        propData.digest = tempTagValue;
                    }
                    else if ([tempTagName isEqualToString:@"desc"])
                    {
                        propData.desc = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"designer"])
                    {
                        propData.designer = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"unit"])
                    {
                        propData.unit= tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"unitid"])
                    {
                        propData.unitid= tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"camerist"])
                    {
                        propData.camerist = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"date"])
                    {
                       propData.date = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"loc"])
                    {
                        propData.loc = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"scale"])
                    {
                        propData.scale = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"imgnum"])
                    {
                        propData.imgnum = tempTagValue;
                    } 
                    else if([tempTagName isEqualToString:@"photo"])
                    {
                        propData.photo = tempTagValue;
                    }
                    else if([tempTagName isEqualToString:@"country"])
                    {
                        propData.country = tempTagValue;
                    }

                }
                else if([currentTag isEqualToString:@"projects"] || 
                           [currentTag isEqualToString:@"imgs"]||
                           [currentTag isEqualToString:@"cchar"]
                           )
                {   
                    if ([tempTagName isEqualToString:@"id"]) 
                    {
                        tempPageInfo.page_id = [tempTagValue intValue];
                    }
                    else if ([tempTagName isEqualToString:@"url"]) 
                    {
                        tempPageInfo.url = [[NSString alloc] initWithString:tempTagValue];
                    }
                    else if ([tempTagName isEqualToString:@"title"])
                    {                        
                        tempPageInfo.title = [[NSString alloc] initWithString:tempTagValue];
                    }
                }
            default: 
                continue;
        }
    }
    
    xmlreader = Nil;
    /*
    if(count == -1 || tag_count <3 )
    {
        UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Data load error. Please try later." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
        [av show];
    }
    else
    {
        int page_count = 0;
        NSMutableDictionary *pageIdDict = [[NSMutableDictionary alloc] init];
        
        for (int i=0; i<[projectsArr count]; i++)
        {
            if([[projectsArr objectAtIndex:i] page_id] == -1)
            {
                [pageIdDict setValue:@"1" forKey:[NSString stringWithFormat:@"%d",page_count]];
                page_count++;
            }
            else if([[projectsArr objectAtIndex:i] page_id]>=0)
            {
                NSNumber *num = [NSNumber numberWithInt:[[projectsArr objectAtIndex:i] page_id]];
                NSString *id = [pageIdDict objectForKey:[NSString stringWithFormat:@"%@",num]];
                
                if(id &&[ id isEqualToString:@"1"]) // if page already exists
                {
                    //do nothing
                }
                else
                {
                    [pageIdDict setValue:@"1" forKey:[NSString stringWithFormat:@"%d",page_count]];
                    page_count++;
                }
            }
        }
        
        gDataSet.page_num = page_count; 
    }
     */

    [[NSNotificationCenter defaultCenter] postNotificationName:msgString object:self];
    
}

-(void) preDefaultGlobalDataToSinglePage:(SinglePageInfo *) tempPageInfo
{
    if (tempPageInfo != Nil) 
    {

    }
}

-(void) makeDataCompatibleWithIPhone
{
    //judge whether is a iphone
    CGRect screen_rect = [[UIScreen mainScreen] bounds];
    if(screen_rect.size.width >= 768 || screen_rect.size.height>=768)
    {
        //ipad
        isIPad = TRUE;
    }
    else//iphone
    {
        gDataSet.bg_img = gDataSet.bg_img_iphone;
        upToolBarInfo.height = upToolBarInfo.height_iphone;
        bottomIndexPage.unit_width = bottomIndexPage.unit_width_iphone;
        bottomIndexPage.unit_height = bottomIndexPage.unit_height_iphone;
        isIPad = FALSE;
    }
}

-(void)reset
{
    if(xmlLoadConnect)
    {
        [xmlLoadConnect cancel];
        [xmlLoadConnect release];
    }
    
    if (xmlDataBuffer) 
    {
        [xmlDataBuffer setLength:0];
        [xmlDataBuffer release];
    }
    
    if (pagesArr) 
    {
        [pagesArr removeAllObjects];
        [pagesArr release];
    }
    
    if (projectsArr) 
    {
        [projectsArr removeAllObjects];
        [projectsArr release];
    }
    
    if (gDataSet)
    {
        [gDataSet reset];
        [gDataSet release];
    }
    
    if(upToolBarInfo)
    { 
        [upToolBarInfo reset];
        [upToolBarInfo release];
    }
    
    if(bottomIndexPage)
    {
        [bottomIndexPage reset];
        [bottomIndexPage release];
    }
}

/*
 else if ([tempTagName isEqualToString:@"align"]) 
 {
 gDataSet.align = tempTagValue;
 }
 else if([tempTagName isEqualToString:@"album_path"])
 {
 gDataSet.albumListPath = tempTagValue;
 }
 else if ([tempTagName isEqualToString:@"auto_screen_fit"]) 
 {
 gDataSet.fit_with_screen = [tempTagValue boolValue];
 }
 else if ([tempTagName isEqualToString:@"page_width"]) 
 {
 gDataSet.page_width = [tempTagValue intValue];
 }
 else if ([tempTagName isEqualToString:@"page_height"]) 
 {
 gDataSet.page_height = [tempTagValue intValue];
 }
 else if([tempTagName isEqualToString:@"fullscreen_mode"])
 {
 gDataSet.fullscreen_mode = [tempTagValue boolValue];
 }
 else if ([tempTagName isEqualToString:@"status_bar_hidden"]) 
 {
 gDataSet.status_bar_hidden = [tempTagValue boolValue];
 }
 else if ([tempTagName isEqualToString:@"fit_page_size"]) 
 {
 gDataSet.fit_page_size = [tempTagValue boolValue];
 }
 else if([tempTagName isEqualToString:@"active_page_num"])
 {
 gDataSet.active_page_num = [tempTagValue intValue];
 
 if (gDataSet.active_page_num <3)
 {
 gDataSet.active_page_num = 3;
 }
 else if(gDataSet.active_page_num>7)
 {
 gDataSet.active_page_num = 7;
 }
 }
 else if( [tempTagName isEqualToString:@"showtoolbar_at_init" ])
 {
 gDataSet.show_toolbar_at_init = [tempTagValue boolValue];
 }
 else if( [tempTagName isEqualToString:@"bg_img"])
 {
 gDataSet.bg_img = tempTagValue;
 }   
 else if([tempTagName isEqualToString:@"bg_img_iphone"])
 {
 gDataSet.bg_img_iphone = tempTagValue;
 }
 else if([tempTagName isEqualToString:@"bg_snd_link"])
 {
 gDataSet.bg_snd_link = tempTagValue; 
 }
 else if([tempTagName isEqualToString:@"bg_snd_play_at_init" ])
 {
 gDataSet.bg_snd_play_at_init = [tempTagValue boolValue];
 }
 else if([tempTagName isEqualToString:@"bg_color"])
 {
 gDataSet.bg_color = tempTagValue;
 }
 else if([tempTagName isEqualToString:@"auto_play_on"])
 {
 gDataSet.auto_play_on = [tempTagValue boolValue];
 }   
 else if([tempTagName isEqualToString:@"auto_play_at_init"])
 {
 gDataSet.auto_play_at_init = [tempTagValue boolValue];
 }
 else if([tempTagName isEqualToString:@"auto_play_time_tick"])
 {
 gDataSet.auto_play_time_tick = [tempTagValue floatValue];
 }
 else if([tempTagName isEqualToString:@"single_page_zoom_min"])
 {
 gDataSet.single_page_zoom_min = [tempTagValue intValue];
 }
 else if([tempTagName isEqualToString:@"single_page_zoom_max"])
 {
 gDataSet.single_page_zoom_max = [tempTagValue intValue];
 }
 else if([tempTagName isEqualToString:@"landscape_two_page"])
 {
 gDataSet.landscape_two_page = [tempTagValue boolValue];
 }
 */

@end
